<template>
  <div class="s-login-containter">
    <div class="s-login-wrap">
      <div class="s-login-bg">
        <img src="@/assets/img/login.png" />
      </div>
      <a-form
        ref="formValidate"
        :model="formState"
        autocomplete="off"
        @finish="onFinish"
        class="s-login-form"
      >
        <div class="s-login-form-top">
          <h1>{{ t("login2") }}</h1>
        </div>
        <div class="s-login-form-content">
          <div class="login-tab-list">
            <div
              :class="['login-tab-item', tabKey === 1 ? 'active' : '']"
              @click="tabKeyChange(1)"
            >
              {{ t("login1") }}
            </div>
            <div>
              <a-select
                :options="languageMap"
                :placeholder="t('login11')"
                v-model:value="defaultLanguage"
                @change="changeLang"
              />
            </div>
          </div>
          <a-form-item name="username">
            <a-input
              :placeholder="t('login4')"
              :value="formState.username"
              @input="onInput"
              @keyup.native.enter.stop.self="onFinish"
            >
              <template #prefix>
                <UserOutlined style="color: rgba(0, 0, 0, 0.25)" />
              </template>
            </a-input>
          </a-form-item>
          <a-form-item name="password">
            <a-input-password
              :placeholder="t('login5')"
              v-model:value="formState.password"
              :maxlength="13"
              @keyup.native.enter.stop.self="onFinish"
              v-input.trim.textFilter
            >
              <template #prefix>
                <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
              </template>
            </a-input-password>
          </a-form-item>
          <a-form-item name="code">
            <div class="login-code">
              <a-input
                style="flex: 1; height: 100%"
                v-model:value="formState.code"
                :placeholder="t('login3')"
                @keyup.native.enter.stop.self="onFinish"
                :maxlength="4"
                v-input.trim.textFilter
              />
              <img
                class="login-code-img"
                :src="
                  `${baseUrl}/analysis/loginImgVerifyCode?uuid=` + randomCode
                "
                @click="changeCode"
              />
            </div>
          </a-form-item>
          <a-form-item name="code">
            <a-checkbox
              v-model:checked="formState.rememberPsd"
              @change="checkboxChange"
              >{{ t("login6") }}</a-checkbox
            >
          </a-form-item>
          <div style="margin: 35px 0 25px">
            <a-form-item :wrapper-col="{ offset: 0, span: 24 }">
              <a-spin :spinning="loginLoading">
                <a-button
                  block
                  type="primary"
                  html-type="submit"
                  :disabled="disabled"
                  >{{ t("login0") }}</a-button
                >
              </a-spin>
            </a-form-item>
            <div>
              <i class="fs11 version-tips">
                {{ t("login7") }}
              </i>
            </div>
          </div>
        </div>
      </a-form>
    </div>
    <div class="s-h5-qrcode">
      <a-image width="150px" :src="isDevEnv || isBuildTest ? h5test : h5prod" />
      <p class="qrcode-tips">{{ t("login10") }}</p>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { uuid } from "vue3-uuid";
import { isResetOldPassword } from "@home/store";
import { formState, loginLoading, defaultLanguage } from "./store";
import { languageMap } from "@/lang/AntDesignLang";
import notify from "./utils";
import { overviewRoute } from "@/routes/config";
import { setLanguage } from "@/lang/tools";
import h5test from "@/assets/img/h5test.png";
import h5prod from "@/assets/img/h5prod.png";
const t = $t;
const userStore = useUserStore();
const setPageLang: any = inject("setPageLang");
const changeLang = (value: any) => {
  setPageLang(value);
  setLanguage(value);
};
const tagStore = useTagStore();
const routeStore = useRouteStore();
const router = useRouter();
const baseUrl = isDevEnv.value
  ? import.meta.env.VITE_URL
  : "/api" + import.meta.env.VITE_URL;
const disabled = computed(() => {
  return (
    isEmptyType(formState.username) ||
    isEmptyType(formState.password) ||
    isEmptyType(formState.code)
  );
});
const onInput = ({ target: { value } }: any) =>
  (formState.username = value.trim());
const randomCode = ref(uuid.v1());
const changeCode = () => {
  loginLoading.value = false;
  formState.code = undefined;
  randomCode.value = uuid.v1();
};
const rememberUserInfo = () => {
  userStore.setRememberPsd(formState.rememberPsd);
  userStore.setUsername(formState.rememberPsd ? formState.username : "");
  userStore.setPassword(formState.rememberPsd ? formState.password : "");
};
const onFinish: any = (values: any) => {
  try {
    if (isKeyboardEvent(values)) return;
    loginLoading.value = true;
    rememberUserInfo();
    const params: any = {
      ...lodash.omit(formState, ["rememberPsd"]),
      uuid: randomCode.value,
    };
    onFinish.timer && clearTimeout(onFinish.timer);
    onFinish.timer = setTimeout(async () => {
      const res = reactive<any>(await loginApi.create(params));
      if (res.code != 200) return message.error(res.message);
      userStore.setToken(res.data.token);
      userStore.setUserinfo(res.data);
      tagStore.clearAllTag();
      isResetOldPassword.value = res.data.needEditPass;
      formState.uid = res.data.userId;
      setLanguage(defaultLanguage.value);
      await routeStore.fetchMenuList();
      cache.local.set("uid", $base64.encode(formState.uid as string));
      clearObjAttr(formState);
      router?.replace(overviewRoute.path);
      notification.success({
        message: $t("login8"),
        description: $t("login9"),
        duration: 2,
      });
      notify({
        title: $t("login8"),
        msg: $t("login9"),
      });
    }, 300);
  } catch (error: any) {
    message.error(error.message);
  } finally {
    loginLoading.value = false;
    changeCode();
  }
};

const tabKey = ref(1);
const tabKeyChange = (key: number) => {
  tabKey.value = key;
};
const checkboxChange = ({ target: { checked } }: any) => {
  rememberUserInfo();
};
onMounted(() => {
  formState.rememberPsd = userStore.rememberPsd;
  if (formState.rememberPsd) {
    formState.username = userStore.username;
    formState.password = userStore.password;
  }
});
</script>
<style scoped lang="less">
.s-login-containter {
  background-image: url(@/assets/img/bg.png);
  background-repeat: no-repeat;
  background-size: 100% 100%;
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  .s-h5-qrcode {
    position: absolute;
    right: 20px;
    bottom: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    row-gap: 10px;
    .qrcode-tips {
      color: #a8abb2;
      margin: 0;
      padding: 0;
      font-weight: bold;
    }
  }
  .s-login-wrap {
    box-shadow: 1px 1px 10px #c1c1c1;
    box-sizing: border-box;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    .s-login-bg {
      width: 500px;
      height: 300px;
      img {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }
    .s-login-form {
      padding: 10px;
      box-sizing: border-box;
      background: #fff;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      .s-login-form-top {
        width: 100%;
        margin-top: 20px;

        .s-icon {
          width: 30px;
          height: 30px;
        }
        h1 {
          width: 100%;
          text-align: center;
          font-size: 22px;
          font-weight: bold;
          margin: 0;
          padding: 0;
        }
      }
      .s-login-form-content {
        width: 300px;

        .login-tab-list {
          display: flex;
          gap: 10px;
          justify-content: space-between;
          align-items: center;
          margin-top: 45px;
          margin-bottom: 30px;
          .login-tab-item {
            font-size: 15px;
            position: relative;
            cursor: pointer;
            &.active {
              color: #1a84ea;
              &::before {
                content: "";
                position: absolute;
                bottom: -4px;
                left: 0;
                width: 100%;
                height: 2px;
                background: #1a84ea;
              }
            }
          }
        }
        .login-code {
          display: flex;
          column-gap: 10px;
          height: 40px;
          .login-code-img {
            height: 100%;
            cursor: pointer;
            border: 1px solid rgb(217, 217, 217);
            box-sizing: border-box;
            flex: 1;
          }
        }
        .version-tips {
          color: #a8abb2;
        }
      }
    }
  }
}
</style>
